package com.jiulong.controller;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;










import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;










import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.alibaba.fastjson.JSONObject;
import com.jiulong.common.utils.HttpUtil;
import com.jiulong.common.utils.MD5Util;
import com.jiulong.dao.TAccountMapper;
import com.jiulong.dao.TGiftMapper;
import com.jiulong.dao.TProductMapper;
import com.jiulong.model.TAccount;
import com.jiulong.model.TAccountExample;
import com.jiulong.model.TFavorite;
import com.jiulong.model.TOrder;
import com.jiulong.model.TOrderExample;
import com.jiulong.model.TOrderdetail;
import com.jiulong.model.TOrderlog;
import com.jiulong.model.TOrdership;
import com.jiulong.model.TProduct;
import com.jiulong.service.AccountService;
import com.jiulong.service.OrderService;





@Controller  
public class IndexControl extends BaseController{
	@Autowired
	TGiftMapper tGiftMapper;
	@Autowired
	com.jiulong.dao.TOrderMapper TOrderMapper;
	@Autowired
	TAccountMapper tAccountMapper;
	@Autowired
	TProductMapper tProductMapper;
	@Autowired
	AccountService accountService;
	@Autowired
	OrderService orderService;
	@RequestMapping("/*")
	public String test1(HttpServletRequest request,HttpServletResponse response,Model model) throws IOException{
	
		return "index";
	}
	//	用户进入主页面判断是否第一次登陆
	@RequestMapping("/indexLogin")
	public String test(HttpServletRequest request,HttpServletResponse response,Model model) throws IOException{
		//code换取opid
		String code=request.getParameter("code");	
    	String urlStr="https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx5724e829db23955a&secret=0b23be4dc38ae1b1d37efc4cd488c685&code="+code+"&grant_type=authorization_code";
    	System.out.println(urlStr);
    	String resXml = HttpUtil.postData(urlStr, null);
    	System.out.println("返回xml：：：："+resXml);
    	JSONObject j=JSONObject.parseObject(resXml);
    	String openid=j.get("openid").toString();
    
    	System.out.println("openid我拿到了哈哈哈！！"+openid);
    	
    	
		//String openid="ohx_wwiIXSM7yFNDcaLymiMeIh9o";
    	
    	HttpSession session = request.getSession();
		session.setAttribute("openid", openid);	
		System.out.println("放进缓存里面的openid "+openid);
	
		
		
		TAccountExample example=new TAccountExample();
		example.createCriteria().andOpenidEqualTo(openid);
		List<TAccount> list=tAccountMapper.selectByExample(example);
		System.out.println(list.toString());
		if(list.toString()=="[]"){
			return "register";
		}
		System.out.println(list.get(0).getAccount());
		session.setAttribute("account", list.get(0).getAccount());				
		return "index";
	}
	@RequestMapping("/ddzf")
	public String ddzf(HttpServletRequest request,HttpServletResponse response,Model model) throws IOException{
		String productId=request.getParameter("productId");
		
		if(productId==null||productId.equals("")){
			return "error1";
		}
		System.out.println(productId);
		//从预订页面拿来的跳转参数

		TProduct product =new TProduct();
		product= tProductMapper.selectByPrimaryKey(Integer.parseInt(productId));
		BigDecimal price=product.getNowprice();
		BigDecimal yuanPrice=product.getPrice();
		String title=product.getTitle();
		String hotelName=product.getName();
		System.out.println("openid取值之前");
		HttpSession session = request.getSession();
		session.setAttribute("productId", productId);
		session.setAttribute("price", price);	
		
		String openid=session.getAttribute("openid").toString();
		//System.out.println("取到真的openid"+openid);
		System.out.println("openid取值之后");
		//String openid="ohx_wwiIXSM7yFNDcaLymiMeIh9o";
		model.addAttribute("hotelName", hotelName);
		model.addAttribute("price", price);
		model.addAttribute("title", title);
		TAccount tAccount=	accountService.findAccountbyId(openid);
		System.out.println("我通过openid找到了用户的昵称！"+tAccount.getAccount());
		System.out.println(tAccount.getNickname());
		System.out.println("openid "+openid);
		model.addAttribute("yuanPrice", yuanPrice);
		
		String tel=tAccount.getTel();
		String cardNo=tAccount.getCardno();
		String nickname=tAccount.getNickname();
		model.addAttribute("nickname", nickname);
		model.addAttribute("tel", tel);
		model.addAttribute("cardNo", cardNo);	
		return "ddzf";
	}
	

	@RequestMapping("/hml")
	public String hml(HttpServletRequest request,HttpServletResponse response) throws IOException{
		return "hml";
	}
	@RequestMapping("/test")
	public String test2(HttpServletRequest request,HttpServletResponse response) throws IOException{
		return "test";
	}
	@RequestMapping("/jdjm")
	public String jdjm(HttpServletRequest request,HttpServletResponse response) throws IOException{
		
		return "jdjm";
	}

	@RequestMapping(value="/grzx1" ,method=RequestMethod.POST)
	public String grzx1(HttpServletRequest request,HttpServletResponse response,Model model) throws IOException{
		String account=request.getParameter("account");
		String user=request.getParameter("user");
		String endtime1=request.getParameter("endtime1");
		String starttime1 =request.getParameter("starttime1");
		//生成订单号
		long currentTimeMillis = System.currentTimeMillis();
	    String strReq =  currentTimeMillis + "jiulongWeiPay";
	    String out_trade_no = strReq; 
		String status="init";
	
		HttpSession session = request.getSession();
		session.getAttribute("price");	
		String amount1=	 session.getAttribute("price").toString();
		 String total_fee1=String.valueOf((Double.valueOf(amount1)*100));
	     String total_fee = total_fee1.substring(0,total_fee1.indexOf("."));
		
		System.out.println(amount1);
	
		BigDecimal amount=new BigDecimal(amount1); 
		BigDecimal fee  =new BigDecimal(0);
		BigDecimal ptotal  =amount ;
		int quantity  =1;
		String 	paystatus= "n";
		String updateAmount="n";
		TOrder order=new TOrder();
	
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
			String date=df.format(new Date());
			System.out.println(df.format(new Date()));// new Date()为获取当前系统时间
			try{	order.setCreatedate(date);}catch(Exception e){
				e.printStackTrace();
			}
	
		order.setAccount(account);
		order.setUser(user);
		order.setEndtime1(endtime1);
		order.setStarttime1(starttime1);
		order.setStatus(status);
		order.setAmount(amount);
		order.setFee(fee);
		order.setPtotal(ptotal);
		order.setQuantity(quantity);
		order.setPaystatus(paystatus);
		order.setUpdateamount(updateAmount);
	
		
		
		String productId= session.getAttribute("productId").toString();
		TProduct product =new TProduct();
		product= tProductMapper.selectByPrimaryKey(Integer.parseInt(productId));
		String productName=product.getName();
		String productIntroduce=product.getIntroduce();
		String imageUrl1=product.getPicture();
		String imageUrl="http://threeshop1.oss-cn-hangzhou.aliyuncs.com"+imageUrl1;
		//expresscode:此处作为产品名字
		order.setExpresscode(productName);
		//expressno:图片路径
		order.setExpressno(imageUrl);
		//expressnname:产品介绍
		order.setExpressname(productIntroduce);
		//remark：此处作为订单号的记录
		order.setRemark(out_trade_no);
		orderService.insertOrder(order);
		int orderId = 0;
	try{
		//获取订单id
		TOrderExample example=new TOrderExample();
		example.createCriteria().andRemarkEqualTo(out_trade_no);
		List<TOrder> orderList=TOrderMapper.selectByExample(example);
		orderList=TOrderMapper.selectByExample(example);
	    orderId=orderList.get(0).getId();
	}catch(Exception e){
		System.out.println("获取订单id异常！");
		e.printStackTrace();
	}
	//开始插入订单信息
		try{
	
		TOrderdetail detail=new TOrderdetail();
		detail.setOrderid(orderId);

		orderService.insertOrderDetail(detail);
		}catch(Exception sql){
			System.out.println("插入详细订单信息异常！");
			sql.printStackTrace();
		}

		
		
	String openid=	session.getAttribute("openid").toString()	;
		//String openid="ohx_wwiIXSM7yFNDcaLymiMeIh9o";
		
		
	TAccount tAccount=	accountService.findAccountbyId(openid);
	String score=tAccount.getScore().toString();
	String rank=tAccount.getRank();

	model.addAttribute("rank", rank);
	model.addAttribute("score", score);
	model.addAttribute("account", account);	
	
	
	String nickname=tAccount.getNickname();
	try{	
		//插入用户的信息
		TOrdership ship=new TOrdership();
		ship.setOrderid(String.valueOf(orderId));
		//查询手机号码和nickname
		ship.setPhone(tAccount.getTel());
		ship.setShipname(nickname);
		//remark作为入住日期
		ship.setRemark(starttime1);
		//tel作为离店日期
		ship.setTel(endtime1);
		//开始插入订单信息
			orderService.insertOrderShip(ship);
			}catch(Exception sql){
				System.out.println("插入详细订单ship信息异常！");
				sql.printStackTrace();
			}

	//插入日志信息
	try{
		TOrderlog log=new TOrderlog();
		log.setOrderid(String.valueOf(orderId));
		log.setAccount(nickname);
		log.setAccounttype("w");
		Calendar c = Calendar.getInstance();
		Date nowTime = c.getTime();
		System.out.println(nowTime);
		log.setCreatedate(nowTime);	
		log.setContent("【创建订单】用户创建订单。订单总金额："+amount);
		orderService.insertOrderLog(log);
	}catch(Exception e){
		System.out.println("订单日志插入失败！");
		e.printStackTrace();
	}
		
	try{
	List gift=orderService.findGiftbyId(nickname);
	
	List list=orderService.findOrderDetailByOpenid(nickname);
	model.addAttribute("detailList", list);
	 model.addAttribute("detailGift", gift);
	}catch(Exception e){
		e.printStackTrace();
	}
		return "grzxDing";
	}
	@RequestMapping("/jdjs")
	public String jdjs(HttpServletRequest request,HttpServletResponse response) throws IOException, Exception{

			/*Calendar c = Calendar.getInstance();
			Date nowTime = c.getTime();
			System.out.println(nowTime);*/
		return "jdjs";
	}
	
	@RequestMapping("/grzx")
	public String grzx(HttpServletRequest request,HttpServletResponse response) throws IOException{
		return "grzx";
	}
	
	@RequestMapping("/jdsp")
	public String jdsp(HttpServletRequest request,HttpServletResponse response) throws IOException{
		
		
		return "jdsp";
	}


	@RequestMapping(value="/login1" ,method=RequestMethod.POST)
	public String login1(HttpServletRequest request,HttpServletResponse response) throws IOException{
		String account=request.getParameter("account");
		String password=request.getParameter("password");
		String encodePassword=	MD5Util.MD5Encode(password, "utf-8");
		
		TAccountExample example=new TAccountExample();
		example.createCriteria().andAccountEqualTo(account);
		List<TAccount> list=tAccountMapper.selectByExample(example);
	
		if(!encodePassword.equals(list.get(0).getPassword())){
			return "error";
		}	
		return "kfyd";
	}
	@RequestMapping(value="/login" ,method=RequestMethod.GET)
	public String yhhd(HttpServletRequest request,HttpServletResponse response) throws IOException{
		return "login";
	}
	
	@RequestMapping("/yhhd1")
	public String yhhd1(HttpServletRequest request,HttpServletResponse response) throws IOException{
		return "yhhd";
	}
	@RequestMapping("/wjmm")
	public String wjmm(HttpServletRequest request,HttpServletResponse response) throws IOException{
		return "wjmm";
	}

	@RequestMapping(value="/register1",method=RequestMethod.POST)
	public String register1(HttpServletRequest request,HttpServletResponse response) throws IOException{

		String account=request.getParameter("account");
		MD5Util md=new MD5Util();
		String password1=request.getParameter("password");
		String newPassword=request.getParameter("newpassword");
		if(!password1.equals(newPassword)){
	
		
			return "error";
		}
		
		HttpSession session = request.getSession();
		//String openid="ohx_wwiIXSM7yFNDcaLymiMeIh9o";
		String openid=session.getAttribute("openid").toString();
			//读取用户新
		//JSONObject j=getAccount.weixin_payGetAccount(openid);
		//微信昵称
    	//String cardtype=j.get("nickname").toString();
    	//String postcode=j.get("headimgurl").toString();
		String password=md.MD5Encode(password1, "utf-8");
		String cardNO=request.getParameter("cardNo");
		
		String nickname=request.getParameter("nickname");
		String tel=request.getParameter("tel");
		String email=request.getParameter("email");
		
		TAccount tAccount=new TAccount();
			tAccount.setAccount(account);
			tAccount.setPassword(password);
			tAccount.setCardno(cardNO);
			tAccount.setTel(tel);
			tAccount.setEmail(email);
			tAccount.setNickname(nickname);
			tAccount.setOpenid(openid);
		//	tAccount.setPostcode(postcode);
			//tAccount.setCardtype(cardtype);
		  tAccountMapper.insertSelective(tAccount);
		  	
		return "index";
	}	
	@RequestMapping("/register")
	public String register(HttpServletRequest request,HttpServletResponse response) throws IOException{
		return "register";
	}
}
